<template>
  <el-container class="container">
    <el-aside width="200px" class="aside">Aside</el-aside>
    <el-container>
      <el-header class="header">Header</el-header>
      <el-main class="main">
        <!-- 组件方式写法 -->
        <FormBuilder
          ref="formBuilderRef"
          :formItems="formItems"
          v-model="formData"
          :rules="rules"
        >
          <!-- <template #code>我自己处理验证码</template> -->
        </FormBuilder>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
        <hr />
        formData: {{ formData }}

        <hr />
        函数方式写法
        <FormBuilders></FormBuilders>
        <el-button type="primary" @click="handleSubmit2">提交2</el-button>
      </el-main>
      <el-footer class="footer">Footer</el-footer>
    </el-container>
  </el-container>
</template>
<script setup lang="ts">
import HelloWorld from '@/components/HelloWorld.vue'
/**
 * 动态表单绑定数据
 */
const formData = ref({
  name: '',
  age: 0,
})

/**
 * 动态表单数据
 */
const formItems = computed(() => [
  {
    label: '姓名',
    key: 'name',
    type: 'input',
    placeholder: '请输入姓名',
    clearable: true,
    span: 12,
  },
  {
    label: '年龄',
    key: 'age',
    type: 'number',
    props: {
      placeholder: '请输入年龄',
    },
    span: 12,
  },
  {
    label: '性别',
    key: 'sex',
    type: 'select',
    // hidden: false,
    hidden: formData.value?.name === '张三',
    placeholder: '请选择性别',
    options: [
      { label: '男', value: 1 },
      { label: '女', value: 2 },
    ],
  },
  {
    label: '爱好',
    key: 'hobby',
    type: () => h('div', {}, '爱好'),
  },
  {
    label: '手机号',
    key: 'phone',
    type: HelloWorld,
    props: {
      placeholder: '请输入手机号',
    },
  },
  {
    label: '验证码',
    key: 'code',
    // type: 'input',
    placeholder: '请输入验证码',
  },
])

/**
 * 校验规则
 */
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 100,
      message: '年龄必须在 1 到 100 之间',
      trigger: 'blur',
    },
  ],
}
/**
 * 表单实例对象
 */
const formBuilderRef = useTemplateRef('formBuilderRef')
/**
 * 提交
 */
const handleSubmit = () => {
  formBuilderRef.value?.validate((valid: boolean) => {
    if (!valid) return
    console.log('校验通过')
  })
}

/**
 * 组合式函数
 */
const { FormBuilders, validate } = useFormBuilder({
  rules,
  formItems,
  modelValue: formData,
})
/**
 * 提交
 */
const handleSubmit2 = () => {
  validate().then((valid: boolean) => {
    if (!valid) return
    console.log('校验通过')
  })
}
</script>

<style scoped>
.container {
  height: 100vh;
}
.aside {
  background-color: #d3dce6;
  padding: 20px;
}
.header,
.footer {
  background-color: #b3c0d1;
  text-align: center;
  line-height: 60px;
}
.main {
  background-color: #e9eef3;
  padding: 20px;
}
</style>
